<template>
  <div class="search">
    <input type="text" placeholder="请输入城市名称" v-model.trim="cityData" />
    <ul v-if="cityData.trim()">
      <p class="css-1" v-if="isNetworkError">对不起网络似乎出了点问题 请稍后再查询</p>
      <p class="css-2" v-else-if="!isCityExist">似乎没有找到你查找的城市</p>
      <li v-else @click="selectCity(fullCityName)">{{ fullCityName }}</li>
    </ul>
  </div>
  <div v-if="!cityData.trim()">
  <h2 class="text" v-if="data.length === 0">
    暂时没有保存过城市天气信息,&nbsp; 请查询后点击右上角"+"保存。
  </h2>
  <div class="cityinfo" v-else>
    <div
      class="city"
      v-for="item in data"
      :key="item.name"
      @mouseenter="item.showBtns = true"
      @mouseleave="item.showBtns = false"
    >
      <div
        class="city-content"
        :style="{ width: item.showBtns ? '80%' : '100%' }"
      >
        <h3>{{ item.name }}</h3>
        <span>{{ item.temp }}度</span>
      </div>
      <div class="btns" :style="{ display: item.showBtns ? 'flex' : 'none' }">
        <button @click="handleParams(item.name)">查看</button>
        <button @click="handleRemove(item.name)">删除</button>
      </div>
    </div>
  </div>
  </div>

</template>

<script setup>
import { ref ,watch ,onMounted} from 'vue'
import { useRouter,useRoute } from 'vue-router'
import { getCityData, getWeatherData } from '@/api'
const router = useRouter()
const route = useRoute()
const cityData = ref('')
const data = ref(JSON.parse(localStorage.getItem('savedCities') || '[]'))
const isCityExist = ref(null)
const isNetworkError = ref(false)
const fullCityName = ref('')
//点击跳转到对应城市天气情况
const handleParams =async(name) => {
  try{
    const res = await getCityData(name);
    const adcode = res.geocodes[0].adcode;
    if(!adcode){
      return
    }
    router.push({ path:`/weather/${adcode}` , query: { search:name } })
    }catch(err){
      console.log('获取失败')
    }
}
//删除功能
const handleRemove = (name) => {
  const current = JSON.parse(localStorage.getItem('savedCities') || '[]')
  const updated = current.filter(item => item.name !== name)
  localStorage.setItem('savedCities', JSON.stringify(updated))
  data.value = updated
}
const selectCity = async(cityName) => {
    try{
      const res = await getCityData(cityName);
      const adcode = res.geocodes[0].adcode;
      if(!adcode){
        return
      }
      cityData.value = ''
      router.push({ path:`/weather/${adcode}` , query: { search:cityName } })
         }catch(err){
      console.log('获取失败')
    }
}
const syncData = () => {
  data.value = JSON.parse(localStorage.getItem('savedCities') || '[]')
}
//定时更新存储城市的温度
const batchUpdateTemps = async () => {
  const currentCities = JSON.parse(localStorage.getItem('savedCities') || '[]')
  if (currentCities.length === 0) return
  const batchSize = 5 
  const updatedCities = [...currentCities]
  try {
    for (let i = 0; i < updatedCities.length; i += batchSize) {
      const batch = updatedCities.slice(i, i + batchSize)
      const batchResults = await Promise.all(
        batch.map(async (city) => {
          try {
            const cityRes = await getCityData(city.name)
            const adcode = cityRes?.geocodes?.[0]?.adcode
            if (!adcode) return { ...city, temp: 'N/A' }
            const weatherRes = await getWeatherData(adcode, 'base')
            const temp = weatherRes?.lives?.[0]?.temperature || 'N/A'
            return { ...city, temp, lastUpdate: new Date().getTime() }
          } catch (err) {
            console.log(err)
            return { ...city, temp: city.temp || 'N/A' } 
          }
        })
      )
      updatedCities.splice(i, batchSize, ...batchResults)
      await new Promise(resolve => setTimeout(resolve, 500))
    }
    localStorage.setItem('savedCities', JSON.stringify(updatedCities))
    data.value = updatedCities
  } catch (err) {
    console.error('批量更新温度失败', err)
  }
}

onMounted(() => {
  syncData()
    if (data.value.length > 0) {
    batchUpdateTemps()
  }
  setInterval(() => {
    if (data.value.length > 0) batchUpdateTemps()
  }, 3600000)
})
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/weather') {
      syncData()
    }
  }
)
watch(cityData, async (newVal) => {
  if(newVal === ''){
    isCityExist.value = null
    isNetworkError.value = false
    fullCityName.value = ''
    return
  }
  try {
    isNetworkError.value = false
    const res = await getCityData(newVal)
    if (res?.geocodes?.length > 0) {
      isCityExist.value = true
      //匹配
      const { level, province, city, district} = res.geocodes[0]
      switch (level) {
        case '省':
          fullCityName.value = province
          break
        case '市':
          fullCityName.value = city
          break
        case '区县':
          fullCityName.value = district
          break
        default:
        fullCityName.value = district 
      }
    } else {
      isCityExist.value = false
      fullCityName.value = ''
    }
  } catch (error) {
    isNetworkError.value = true
    isCityExist.value = null
    fullCityName.value = ''
  }
})
</script>

<style scoped>
.search {
  position: relative;
  padding-top: 1rem;
  margin-bottom: 2rem;
  input {
    width: 100%;
    background-color: transparent;
    border-bottom-width: 1px;
    padding-left: 0.25rem;
    padding-right: 0.25rem;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    font-family: inherit;
    font-size: 100%;
    font-weight: inherit;
    line-height: inherit;
    color: inherit;
    margin: 0;
    border-color: var(--weather-secondary);
    &::placeholder {
      color: #9ca3af;
      font-size: 17px;
      font-weight: 400;
    }
    &:focus {
      border-color: transparent;
      outline: none;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
  }
  ul {
    /* display: none; */
    position: absolute;
    width: 100%;
    background-color: rgba(0, 78, 113, 1);
    color: rgba(255, 255, 255, 1);
    list-style: none;
    top: 62px;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    padding-left: 0.25rem;
    padding-right: 0.25rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
      0 2px 4px -2px rgba(0, 0, 0, 0.1);
    /* .css-1,
    .css-2 {
      display: none;
    } */
    li {
      padding-top: 0.5rem;
      padding-bottom: 0.5rem;
      cursor: pointer;
    }
  }
}
.text {
  font-size: inherit;
  font-weight: inherit;
  text-align: center;
  transition-duration: 0.2s;
}
.cityinfo {
  margin-top: 2.5rem;
  max-height: 300px;
  overflow-y: scroll;
  scrollbar-width: thin;
  scrollbar-color: initial initial;
  overflow: overlay;
  &:hover::-webkit-scrollbar-thumb:hover {
    background-color: #93c5fd !important;
  }
  .city {
    display: flex;
    justify-content: space-between;
    .city-content {
      display: flex;
      justify-content: space-between;
      transition-duration: 0.3s;
      margin-bottom: 1rem;
      background-color: rgba(0, 78, 113, 1);
      padding-top: 0.5rem;
      padding-bottom: 0.5rem;
      padding-left: 1rem;
      padding-right: 1rem;
      cursor: pointer;
      h3 {
        font-size: inherit;
        font-weight: inherit;
      }
    }
  }
  .btns {
    margin-bottom: 1rem;
    gap: 0.5rem;
    button {
      background-color: rgba(234, 179, 8, 1);
      text-align: center;
      width: 80px;
      cursor: pointer;
      -webkit-appearance: button;
      appearance: button;
      text-transform: none;
      font-family: inherit;
      font-size: 100%;
      font-weight: inherit;
      line-height: inherit;
      color: inherit;
      margin: 0;
      padding: 0;
    }
  }
}
</style>
